//
//  EncryptData.m
//  ebook
//
//  Created by 吴超飞 on 16/9/6.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "EncryptData.h"

#define kDecrySaltKey @"Change-the-world-with-code"
#define kDecrySaltKeyData [kDecrySaltKey dataUsingEncoding:NSUTF8StringEncoding]
#define kDecrySaltKeyBytes (Byte *)[kDecrySaltKeyData bytes]
#define kDecrySaltKeyBytesSize (int)[kDecrySaltKeyData length]

@implementation EncryptData

typedef unsigned char BYTE;
const int ENCRYPT_SIZE = kDecrySaltKeyBytesSize;
//const unsigned char m_bufCode[] = {53, 49, 48, 48};
void Encrypt(void* pBuf, int nSize)
{
    if (!pBuf || nSize <= 0)
        return;
    const uint8_t *keyBytes = kDecrySaltKeyBytes;
    
    BYTE* buf = (BYTE*)pBuf;
//    printf("Begin Encry:");
    for (int i=0; i<nSize; i++)
    {  
//        printf("原:%d ",buf[i]);
        BYTE c = (buf[i] << (i%8)) + (buf[i] >> (8 - i%8));
        buf[i] = c^keyBytes[i%ENCRYPT_SIZE];
//        printf("密:%d \n",buf[i]);
    }
}

void Decrypt(void* pBuf, int nSize)
{
    if (!pBuf || nSize <= 0)
        return;
    const uint8_t *keyBytes = kDecrySaltKeyBytes;
    
    BYTE* buf = (BYTE*)pBuf;
//    printf("Begin Decry:");
    for (int i=0; i<nSize; i++)
    {
//        printf("原：%d  ",buf[i]);
        BYTE c = buf[i]^keyBytes[i%ENCRYPT_SIZE];
        buf[i] = (c >> (i%8)) + (c << (8 - i%8));
//        printf("解：%d\n",buf[i]);
    }
}

+(NSDictionary *)decryptData:(NSData *)data{
    
    char *bytes = (char *)[data bytes];
    int size = (int)data.length;
    Decrypt(bytes, size);
//    NSString *ret = [NSString stringWithFormat:@"%s",bytes];
    NSData *data2 =  [NSData dataWithBytes:bytes length:size];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
//    MTLog(@"bookfile.tar解密后:%@ \n",dict);
    
    return dict;
}

+(void)writeToFile:(NSData *)buffer{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *file = [PATH_OF_DOCUMENT stringByAppendingPathComponent:@"testfile.tar"];
    if (![fm fileExistsAtPath:file]) {
        [fm createFileAtPath:file contents:nil attributes:nil];
    }
    
    NSFileHandle *outFile;
    outFile = [NSFileHandle fileHandleForWritingAtPath:file];
    
    if(outFile == nil)
    {
        MTLog(@"Open of file for writing failed");
    }
    [outFile seekToEndOfFile];
    [outFile writeData:buffer];
    [outFile closeFile];
}

+(NSData *)readFile{

    NSString *file = [[NSBundle mainBundle]pathForResource:@"bookfile" ofType:@"tar"];//[PATH_OF_DOCUMENT stringByAppendingPathComponent:@"testfile.tar"];
    
    NSFileHandle *inFile;
    inFile = [NSFileHandle fileHandleForReadingAtPath:file];
    NSData *data = [inFile readDataToEndOfFile];
    [inFile closeFile];
    
    return data;
}

+(void)decryptBookfile{
    NSString *path = [[NSBundle mainBundle]pathForResource:@"bookfile" ofType:@"tar"];
    NSData *data =[NSData dataWithContentsOfFile:path];
    [EncryptData decryptData:data];
}

+(void)testDecrypt{
//    NSString *str = @"中文QWas12";//@"qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPLKJHGFDSAZXCVBNM";//@"测试中英文混排加密解密QWERTasdfg12345";
//    NSData *data = DataWithString(str);

    NSString *path = [[NSBundle mainBundle]pathForResource:@"chapterlist" ofType:@"json"];
    NSData *data =[NSData dataWithContentsOfFile:path];
    int size = (int)data.length;
    char *bytes = (char *)[data bytes];
//    Encrypt(bytes, size);
//    printf("加密：%s\n",bytes);
//    [EncryptData writeToFile:[NSData dataWithBytes:bytes length:size]];
    
//    NSData *data1 = [EncryptData readFile];
//    int size1 = (int)data1.length;
//    char *bytes1 = (char *)[data1 bytes];
    Decrypt(bytes, size);
    printf("解密：%s\n", bytes);
}


/**
 DES加密解密
 */
/*
+(NSData*) decryptDataUseDES:(NSData *)cipherData key:(NSString*)key{
    
    long size = cipherData.length+1;//缓存空间大小不要写死，比实际大小多给一点，实际不加1也可以，但是减一肯定失败
    unsigned char buffer[size];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    
    // IV 偏移量不需使用
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionECBMode,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          NULL,
                                          [cipherData bytes],
                                          [cipherData length],
                                          buffer,
                                          size,
                                          &numBytesDecrypted);
    
    NSData* data = nil;
    if (cryptStatus == kCCSuccess) {
        data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
    }else{
        MTLog(@"DES解密失败");
    }
    return data;
}
    
+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
    {
        NSData *data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        unsigned char buffer[1024];  //注意空间大小
        memset(buffer, 0, sizeof(char));
        size_t numBytesEncrypted = 0;
        
        CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                              kCCAlgorithmDES,
                                              kCCOptionPKCS7Padding | kCCOptionECBMode,
                                              [key UTF8String],
                                              kCCKeySizeDES,
                                              nil,
                                              [data bytes],
                                              [data length],
                                              buffer,
                                              1024,  //注意空间大小
                                              &numBytesEncrypted);
        
        NSString* plainText = nil;
        if (cryptStatus == kCCSuccess) {
            NSData *dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
            plainText = [dataTemp base64EncodedString];
        }else{
            NSLog(@"DES加密失败");
        }
        return plainText;
    }
*/
@end
